package com.lagou.controller;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@RestController
@RequestMapping("/email")
public class EmailController {
    @GetMapping("/sendEmail/{email}/{code}")
    public boolean sendEmail(@PathVariable String email,@PathVariable String code){
        System.out.println("验证码发送处理begin"+email+code);

        return sendEmailService(email,code);
    }

    //用 1685953024@qq.com发邮件，email邮箱接收
    public boolean sendEmailService(String email,String code){
        System.out.println("发送地址："+email+"验证码："+code);
        try {
            //创建一个配置文件并保存
            Properties properties = new Properties();

            properties.setProperty("mail.host","smtp.qq.com");

            properties.setProperty("mail.transport.protocol","smtp");

            properties.setProperty("mail.smtp.auth","true");


            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //创建一个session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1685953024@qq.com","kszpymnubnjcddib");//16位授权码
                }
            });

            //开启debug模式
            session.setDebug(true);

            //获取连接对象
            Transport transport = session.getTransport();

            //连接服务器
            transport.connect("smtp.qq.com","1685953024@qq.com","kszpymnubnjcddib");//16位授权码

            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);

            //邮件发送人
            mimeMessage.setFrom(new InternetAddress("1685953024@qq.com"));

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(email));

            //邮件标题
            mimeMessage.setSubject("验证码测试");

            //邮件内容
            mimeMessage.setContent(code,"text/html;charset=UTF-8");

            //发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

            //关闭连接
            transport.close();
        }catch (Exception e){
            return false;
            //e.printStackTrace();
        }
        return true;
    }
}
